<?php
/**
 * 自定义指令
 * 【作用于自定义回复，请绝对不要删除】
 */
class weixin_cmd_custom extends mc_weixin_cmd
{
	protected $name = '自定义回复';
	protected $keyword = '';
	protected $intro = "自定义指令的回复内容";

	protected $menu_types = array('text','click');

	public function describe()
	{
		return false;
	}

	public function describe_by_role_obj($role_obj, $menu_type)
	{
		if(!$this->menu_type_exists($menu_type)) return false;
		$custom_obj = _G('loader')->model('weixin:custom_cmd');
		$list = $custom_obj->find_all('*', array('mp_id'=>$role_obj->id));
		$result = array();
		if($list) while ($val=$list->fetch_array()) {
			$result[] = array(
				'name' => $val['intro'],
				'keyword' => $val['keyword'],
				'intro' => $val['intro'],
				'roles' => $role_obj->role
			);
		}
		return $result;
	}

	public function match($message_obj, $role_obj, $session_obj)
	{
		$detail = $this->get_custom_cmd($message_obj, $role_obj);
		return !empty($detail);
	}

	public function execute($message_obj, $role_obj, $session_obj)
	{
		//重置微信指令会话
		$session_obj->action = mc_weixin_session::ACTION_RESET;
		
		$cmd = $this->get_custom_cmd($message_obj, $role_obj);
		if(!$cmd) return false;
		
		//回复微信用户
		$cmd->reply($message_obj->FromUserName, $message_obj->ToUserName, $role_obj);
	}

	private function get_custom_cmd($message_obj, $role_obj)
	{
		$cmd = null;
		$mark = strtolower('custom_cmd_');
		$keyword = $this->get_keyword($message_obj);
		//通过指定ID方式
		if(preg_match("/^{$mark}([0-9]+)$/", $keyword, $match)) {
			$id = (int)$match[1];
			if($id > 0) {
				$cmd = mc_weixin_custom_cmd::read($id);
			}
		} else {
	        if(strtolower(G('charset')) != 'utf-8') {
	            $keyword = charset_convert( $keyword, 'utf-8', G('charset') );
	        }
			//通过关键字形式
			$cmd = mc_weixin_custom_cmd::read_by_keyword($role_obj->id, $keyword);
		}

		return $cmd;
	}

	private function get_keyword($message_obj)
	{
		if($message_obj->MsgType == 'event' && $message_obj->Event == 'CLICK') {
			$keyword = trim($message_obj->EventKey);
		} else {
			$keyword = trim($message_obj->Content);
		}
		return $keyword;
	}

}
/** end **/